<!-- 新建样品组件 -->
<template>
  <div style="width: 100%; overflow: hidden">
    <van-popup
      v-model="show"
      :style="{ height: '100%', width: '100%' }"
      class="fa"
      position="left"
    >
      <van-form
        style="height: 100%; overflow: auto; box-sizing: border-box"
        @submit="onSubmit"
      >
        <div
          style="position: fixed; top: 0; left: 0; width: 100%; z-index: 999"
        >
          <!-- 引入公共头部组件 -->
          <HeaderMenu
            :rightText="rightText"
            :title="title + '样品'"
            leftText="返回"
            @rightEvent="addPerson"
          />
        </div>
        <div class="client" style="padding-top: 50px">
          <van-field
            v-model="entity.CustomerName"
            :disabled="disabled"
            :rules="[{ required: true, message: '请选择客户' }]"
            label="客户名称："
            placeholder="请选择客户"
            readonly
            right-icon="edit"
            @click="CustomerChoice"
          >
          </van-field>
          <van-field
            :disabled="disabled"
            :value="entity.ApplyDate"
            label="申请日期："
            placeholder="请选择日期"
            @click="readonly ? (showDate = false) : (showDate = true)"
          />

          <van-field
            v-model="entity.Addressee"
            :disabled="disabled"
            :rules="[{ required: true, message: '请输入收件人' }]"
            label="收件人"
            placeholder="收件人"
            @click="showPickerClick"
          />
          <!-- 收件人弹窗 -->
          <van-popup v-model="showPicker" position="bottom">
            <van-picker
              :columns="columns"
              show-toolbar
              value-key="Addressee"
              @cancel="showPicker = false"
              @confirm="onConfirmAddressee"
            />
          </van-popup>
          <!-- :rules="[{ required: true, message: '请输入经办人' }]" -->
          <van-field
            :disabled="disabled"
            readonly
            @click="showPickerClickRealName('经办人')"
            label="经办人"
            placeholder="经办人"
            v-model="entity.RealName"
          />
          <!-- 经办人弹窗 -->
          <van-popup v-model="showPickerRealName" position="bottom">
            <van-picker
              show-toolbar
              value-key="RealName"
              :columns="columnsRealName"
              @confirm="onConfirmRealName"
              @cancel="showPickerRealName = false"
            />
          </van-popup>

          <!-- 紧急程度 -->
          <!--   :rules="[{ required: true, message: '请输入紧急程度' }]" -->
          <van-field
            :disabled="disabled"
            readonly
            @click="showPickerClickRealName('紧急程度')"
            label="紧急程度"
            placeholder="紧急程度"
            v-model="entity.Urgency"
          />
          <!-- 紧急程度弹窗 -->
          <van-popup v-model="showPickerUrgency" position="bottom">
            <van-picker
              show-toolbar
              value-key="Urgency"
              :columns="columnsUrgency"
              @confirm="onConfirmUrgency"
              @cancel="showPickerUrgency = false"
            />
          </van-popup>

          <!-- 样品用途 -->
          <!--  :rules="[{ required: true, message: '请输入样品用途' }]" -->
          <van-field
            :disabled="disabled"
            readonly
            @click="showPickerClickRealName('样品用途')"
            label="样品用途"
            placeholder="样品用途"
            v-model="entity.Purpose"
          />
          <!-- 样品用途弹窗 -->
          <van-popup v-model="showPickerPurpose" position="bottom">
            <van-picker
              show-toolbar
              value-key="Purpose"
              :columns="columnsPurpose"
              @confirm="onConfirmPurpose"
              @cancel="showPickerPurpose = false"
            />
          </van-popup>

          <van-field
            :rules="telRules"
            v-model="entity.AddresseeTel"
            :disabled="disabled"
            label="收件电话"
            placeholder="收件电话"
          />
          <van-field
            v-model="entity.ReceiveAddress"
            :disabled="disabled"
            :rules="[{ required: true, message: '请输入收获地址' }]"
            label="收货地址"
            placeholder="收货地址"
          />
          <van-field
            v-model="entity.SampleTrialRemark"
            :disabled="disabled"
            autosize
            label="试用说明:"
            type="textarea"
          />
          <van-field
            :disabled="disabled"
            label="备注:"
            autosize
            type="textarea"
            v-model="entity.Remark"
          />
        </div>

        <!-- 可华东该区域的产品列表 -->
        <div class="scrollBar" style="">
          <van-list
            style="padding-bottom: 50px;"
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoading"
          >
            <!-- mysamplebox -->
            <div
              class=" "
              v-for="(item, index) in data"
              :key="item.Id"
              style=" width: 93%;
                margin: 0 auto;
                box-shadow: 3px 4px 16px 0px #6b6b6a;
                margin-top: 20px;
                margin-bottom: 10px;
                background-color: #ffffff;
                border-radius: 5px;
                padding-top: 1px;
                padding-bottom: 4px;
              "
            >
              <div class="left" style="font-size: 14px; color: #000">
                品名:<span class="font"
                  >{{ item.ProductId }}/{{ item.cInvName }}</span
                >
              </div>
              <div class="left" style="font-size: 14px">
                规格:<span class="font">{{ item.cInvStd || "无" }}</span>
              </div>
              <div class="Fa">
                <span class="left" style="font-size: 14px">数量:</span>
                <van-stepper
                  :disabled="disabled"
                  class="fontstepper"
                  input-width="50px"
                  v-model="item.MainQuantity"
                />
              </div>
              <van-field
                :disabled="disabled"
                class="textarea"
                style=""
                :readonly="readonly"
                label="备注:"
                rows="2"
                autosize
                type="textarea"
                v-model="item.Remark"
                placeholder="备注"
              />
              <div class="delete-list">
                <div
                  v-if="
                    $route.query.readonly == 0 || $route.query.readonly == 1
                  "
                  @click="delte([item.Id], index)"
                  style="
                    width: 15%;
                    border-radius: 5px;
                    line-height: 30px;
                    color: #fff;
                    text-align: center;
                    background-color: red;
                  "
                >
                  删除
                </div>
              </div>
            </div>
          </van-list>
        </div>

        <div v-show="hideshow">
          <div
            style=""
            v-if="$route.query.readonly == 0 || $route.query.readonly == 1"
            class="page-bottom"
          >
            <!-- <van-button
            @click="close"
            style="margin-left: 8px"
            slot="button"
            type="default"
            >关闭</van-button
          > -->
            <div>
              <van-button
                slot="button"
                block
                native-type="submit"
                round
                type="info"
                >提交
              </van-button>
            </div>
          </div>
        </div>
      </van-form>
      <div v-show="hideshow">
        <div
          v-if="$route.query.readonly == 0 || $route.query.readonly == 1"
          class="productButton"
          @click="Add"
        >
          <button v-show="hideshow" class="button">添加产品</button>
        </div>
      </div>
    </van-popup>
    <van-calendar
      v-model="showDate"
      :show-confirm="false"
      @confirm="onConfirm"
    />
    <Myuser ref="myuser" @customerChoice="Client" />
    <!-- 添加产品 -->
    <Product ref="product" @Product="Product" />
    <!-- 添加收件人 -->
    <CustAddress ref="custAddress" />
  </div>
</template>

<script>
import {
  AddressList,
  Calendar,
  Cell,
  CellGroup,
  Col,
  Dialog,
  Field,
  Icon,
  NavBar,
  Popup,
  Row,
  Stepper,
  Toast
} from "vant";
//客户
import Myuser from "../../components/OwnUser.vue";
import Product from "../../components/Product.vue";
// 引入添加收件人组件
import CustAddress from "../../components/custAddress.vue";
// 引入公共头部组件
import HeaderMenu from "../../components/VolHeaderMenu.vue";
// 应用工具函数
export default {
  components: {
    "van-stepper": Stepper,
    "van-calendar": Calendar,
    "van-nav-bar": NavBar,
    "van-icon": Icon,
    "van-popup": Popup,
    "van-row": Row,
    "van-address-list": AddressList,
    "van-field": Field,
    "van-col": Col,
    "van-cell": Cell,
    "van-cell-group": CellGroup,
    Myuser,
    Product,
    HeaderMenu,
    CustAddress
  },
  // props: {
  // readonly: {
  //   type: Boolean,
  //   default: false,
  // },
  // },

  data() {
    return {
      // 解决表单输入移动端键盘弹起导致的页面fixed定位元素布局错乱问题
      docmHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      showHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      hideshow: true, //显示或者隐藏footer
      // 手机格式校验
      telRules: [
        {
          required: true,
          message: "手机号不能为空",
          trigger: blur
        },
        {
          validator: value => {
            console.log('是覅偶正确',value)
            // 手机号正则匹配 后续也可以用到该正则   /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/

            // 以下匹配电话号格式为010-88925890   ，  13847616463， 0731-85985051， 0312-5906070
            let regPhone1=(/^(([0-9]{11})|([0-9]{4}\-[0-9]{8})|([0-9]{4}\-[0-9]{7}))$/)
            let regPhone2=(/^(([0-9]{11})|([0-9]{3}\-[0-9]{8})|([0-9]{4}\-[0-9]{7}))$/)

            return regPhone1.test( value ) || regPhone2.test( value );
          },
          message: "请输入正确的手机号格式",
          trigger: "onBlur"
        }
      ],
      disabled: false,
      title: "新建",
      rightText: "",
      loading: false,
      finished: false,
      readonly: false,
      listClo: [],
      // 收件人列表
      columns: [],
      // 经办人列表
      columnsRealName: [],
      // 紧急程度
      columnsUrgency: [{ Urgency: "一般" }, { Urgency: "紧急" }],
      columnsPurpose: [{ Purpose: "自用" }, { Purpose: "实验" }],
      // 收件人弹窗
      showPicker: false,
      info: {},
      entity: {},
      data: [],
      show: false,
      showDate: false,
      pagination: {
        PageIndex: 1,
        PageRows: 10,
        Total: 0
      },
      Id: "",
      // 是否显示添加收件人按钮
      isAddButton: false,
      // 选中客户ID
      personID: "",
      // 样品用途弹窗
      showPickerPurpose: false,
      // 经办人弹窗
      showPickerRealName: false,
      // 紧急程度弹窗
      showPickerUrgency: false
    };
  },
  created() {
    
    // 2.通过dispatch触发一个actions  储存vuex里的用户id
    this.$store.dispatch("getUserInfoId", {
      url: "/Base_Manage/Home/GetOperatorInfo"
    });
    
    // 判断输入框是否可读
    if (this.$route.query.readonly == 0) {
      // 新建
      this.readonly = false;
      this.title = "新建";
      this.rightText = "";
      this.loading = false;
      this.finished = true;
    } else if (this.$route.query.readonly == 1) {
      // 修改
      this.readonly = true;
      this.title = "修改";
    } else {
      this.title = "查看";
      // 查看
      this.disabled = true;
    }
    console.log(this.$route.query.readonly, this.getNowFormatDate());
    this.openForm(this.$route.query.Id);

    //默认赋值当前选择日期util.formatDate('YY-MM-DD')
    this.$set(this.entity, "ApplyDate", this.getNowFormatDate());
    // 获取缓存里的登录账号名字realname
    let RealName = localStorage.getItem("RealName");
    this.$set(this.entity, "RealName", RealName);

  },
  watch: {
    //监听显示高度
    showHeight: function() {
      if (this.docmHeight > this.showHeight) {
        //隐藏
        this.hideshow = false;
      } else {
        //显示
        this.hideshow = true;
      }
    }
  },
  mounted() {
    //监听事件
    window.onresize = () => {
      return (() => {
        this.showHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
      })();
    };

    // 获取经办人列表
    // this.getRealUserName(); 
  },
  methods: {
    // 获取经办人列表数据
    getRealUserName() {
      this.http.post("Base_Manage/Base_User/GetDataList", {}).then(res => {
        res.Data.forEach(item => {
          let obj = {
            RealName: item.RealName
          };
          this.columnsRealName.push(obj);
        });
        console.log("获取经办人列表this.columnsRealName", this.columnsRealName);
      });
    },

    // 获取当前日期
    getNowFormatDate() {
      var date = new Date();
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },

    // 样品产品列表加载
    onLoading() {
      if (this.$route.query.readonly == 1 || this.$route.query.readonly == 2) {
        this.loading = true; //防止第一页重复加载
        // 获取联系人列表数据
        this.getDataList();
      }
    },
    // 删除
    delte(Id, index) {
      if (Id[0]) {
        this.http
          .post("/SampleManagement/SPL_SampleApplyDetails/DeleteData", Id)
          .then(resJson => {
            Toast("删除成功");
            this.data.splice(index, 1);
            this.getDataList();
          });
      } else {
        this.data.splice(index, 1);
        Toast("操作成功");
      }
    },
    onConfirmAddressee(item) {
      this.$set(this.entity, "Addressee", item.Addressee);
      this.$set(this.entity, "AddresseeTel", item.TelNumber);
      this.$set(this.entity, "ReceiveAddress", item.Address);
      // this.entity.Addressee = item.Name;
      // this.entity.AddresseeTel = item.Tel_Code;
      // this.entity.Addressee = item.Address;
      console.log(item);
      // this.entity.AddresseeTel = Row.Tel_Code;
      // var id = this.listClo.findIndex(item => item.Name == value);
      // console.log(id);
      // if (id != -1) {
      //   this.entity.AddresseeTel = this.listClo[id].Tel_Code;
      // }
      this.showPicker = false;
    },

    // 经办人点击事件
    showPickerClickRealName(item) {
      if (item === "经办人") {
        this.showPickerRealName = true;
      } else if (item === "紧急程度") {
        this.showPickerUrgency = true;
      } else {
        this.showPickerPurpose = true;
      }
    },
    // 经办人弹窗确认事件
    onConfirmRealName(e) {
      // 关闭经办人弹窗
      this.showPickerRealName = false;
      console.log("经办人弹窗确定", this.entity, e);
      this.$set(this.entity, "RealName", e.RealName);
    },
    // 紧急程度弹窗确定事件
    onConfirmUrgency(e) {
      // 关闭紧急程度弹窗
      this.showPickerUrgency = false;
      this.$set(this.entity, "Urgency", e.Urgency);
    },
    // 样品用途弹窗确定事件
    onConfirmPurpose(e) {
      // 关闭样品用途弹窗
      this.showPickerPurpose = false;
      this.$set(this.entity, "Purpose", e.Purpose);
    },

    // 收件人点击事件
    showPickerClick() {
      if (this.$route.query.Id) {
        // 如果客户为空 提示
        if (!this.entity.CustomerName) {
          Toast("请先选择客户");
          return;
        }
        // 如果收件人列表为空 提示先添加收件人
        if (this.columns.length == 0) {
          Dialog.alert({
            message: "请先添加收件人信息",
            confirmButtonColor: "#2472C8",
            confirmButtonText: "确定"
          }).then(() => {
            // on close
          });
        } else {
          // 显示收件人弹窗
          this.showPicker = true;
        }
      } else {
        // 如果客户为空 提示
        if (!this.entity.CustomerName) {
          Toast("请先选择客户");
          return;
        }
        // 如果收件人列表为空 提示先添加收件人
        if (this.columns.length == 0) {
          Dialog.alert({
            message: "请先添加收件人信息",
            confirmButtonColor: "#2472C8",
            confirmButtonText: "确定"
          }).then(() => {
            // on close
          });
        } else {
          // 显示收件人弹窗
          this.showPicker = true;
        }
      }
    },
    // 添加收件人按钮事件
    addPerson() {
      // 父组件直接通过refs获取子组件里的data变量赋值
      this.$refs.custAddress.fieldListParams.CustomerId = this.entity.CustomerId;
      // 打开添加收件人弹窗组件
      this.$refs.custAddress.openForm();
    },

    swipeleft() {
      this.show = false;
    },
    touchstart(e) {
      // alert("123");

      // e.preventDefault();

      this.startX = e.touches[0].clientX;
      this.startY = e.touches[0].clientY;
    },
    touchmove(e) {
      //    this.show = false;
      // e.preventDefault();
      this.moveX = e.touches[0].clientX;
      this.moveY = e.touches[0].clientY;
      // this.startX - this.moveX <= 0
      //   ? console.log("你在往右滑")
      //   : console.log("你在往左滑");
    },

    formatDate(date) {
      const time = new Date(date);
      const y = time.getFullYear();
      return `${y}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    onConfirm(date) {
      this.showDate = false;
      this.entity.ApplyDate = this.formatDate(date);
    },
    //返回
    onClickLeft() {
      this.$router.go(-1);
      this.show = false;
    },
    //选中的产品
    Product(a) {
      a.forEach(item => {
        this.data.push({
          ProductId: item.cInvCode,
          cInvName: item.cInvName,
          cInvCode: item.cInvCode,
          cInvStd: item.cInvStd
        });
      });
    },

    // 选择产品页面;
    Add() {
      this.$refs.product.openForm();
    },
    //关闭
    close() {
      this.show = false;
      this.$router.go(-1);
    },
    //本条客户的数据
    Client(a) {
      // 先赋值选中的客户id
      this.personID = a.Id;
      this.$set(this.entity, "Addressee", "");
      this.$set(this.entity, "AddresseeTel", "");
      this.$set(this.entity, "ReceiveAddress", "");
      this.$set(this.entity, "CustomerName", a.cCusName);
      this.entity.CustomerId = a.Id || a.cCusCode;
      this.contactPerson(a.Id);
      // 选中客户后显示添加收件人按钮
      // this.isAddButton = true;
      this.rightText = "添加收件人";
    },

    // 获取收件人信息列表
    contactPerson() {
      this.http
        .post(
          "/CustomerManagement/Cust_AddressBook/GetDataListByMoreCondition",
          {
            Search: [
              {
                Condition: "CustomerId",
                Keyword: this.personID
              }
            ],
            ...this.filters
          }
        )
        .then(resJson => {
          this.columns = resJson.Data;
          this.listClo = resJson.Data;
        });
    },
    //选择客户
    CustomerChoice() {
      this.$refs.myuser.openForm();
      // if (!this.Id) {

      // }
    },
    // 获取样品详情
    getDataList() {
      if (this.$route.query.readonly == 0) {
        this.loading = false;
        return;
      }
      this.http
        .post("/SampleManagement/SPL_SampleApplyMain/GetTheDataOfAll", {
          PageIndex: this.pagination.PageIndex,
          PageRows: 10,
          SortField: "Id",
          SortType: "desc",
          Search: {
            Condition: "Id",
            Keyword: this.Id
          }
        })
        .then(res => {
          if (res.Success) {
            this.entity = res.Data;
              // 获取缓存里的登录账号名字realname
            let RealName = localStorage.getItem("RealName");
            this.$set(this.entity, "RealName", RealName?RealName:"");
            if (res.Data.SSAD_List.length == 0) {
              // 停止加载
              this.loading = false;
              // 数据全部加载完成
              this.finished = true;
              return;
            }
            this.data = res.Data.SSAD_List;
            this.$set(
              this.entity,
              "ApplyDate",
              this.entity.ApplyDate
                ? this.entity.ApplyDate.substring(0, 10)
                : ""
            );
            // 赋值客户id获取客户收件人列表
            // 赋值客户id获取客户收件人列表
            this.personID = this.entity.CustomerId;
            this.contactPerson();

            // 停止加载
            this.loading = false;
            // 数据全部加载完成
            this.finished = true;
          } else {
            // 停止加载
            this.loading = false;
            // 数据全部加载完成
            this.finished = true;
            Toast(res.Msg);
          }
        });
    },
    init() {
      this.Id = "";
      this.show = true;
      (this.data = []), (this.entity = {});
    },
    // 样品提交
    onSubmit() {
      if (this.data.length == 0) {
        Dialog.alert({
          message: "请先添加产品",
          confirmButtonColor: "#2472C8",
          confirmButtonText: "确定"
        }).then(() => {
          this.Add();
          // on close
        });

        return;
      }

      this.$set(this.entity, "Transactor", this.info.Id);
      var entityData = { ...this.entity };
      var SSAD_List = [...this.data];
      entityData.SSAD_List = SSAD_List;
      console.log("创建成功", entityData);
      this.http
        .post("/SampleManagement/SPL_SampleApplyMain/SaveData", entityData)
        .then(resJson => {
          if (resJson.Success) {
            if (this.$route.query.readonly == 0) {
              Toast("创建成功");
            } else {
              Toast("修改成功");
            }
            this.show = false;
            console.log(this.$parent);
            this.$router.back();
            // this.$parent.getDataList();
          } else {
            Toast(resJson.Msg);
          }
        });
    },
    openForm(Id) {
      this.init();
      if (Id) {
        this.Id = Id;
        this.getDataList();
      }
    }
  }
};
</script>

<style scoped>
.productButton {
  position: fixed;
  bottom: 0;
  width: 91%;
  padding-left: 15px;
  padding-right: 15px;
  height: calc(
    47px + constant(safe-area-inset-bottom)
  ); /* 直接扩展高度，因为padding-bottom是内边距 */
  height: calc(47px + env(safe-area-inset-bottom)); /* 直接扩展高度 */
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.button {
  width: 100%;
  height: 36px;
  border-radius: 5px;
  background-color: rgb(19, 236, 70);
  color: #ffffff;
  font-size: 14px;
  outline: none;
  border: none;
}

/* 适配底部导航栏 */
.page-bottom {
  position: fixed;
  bottom: 0;
  background-color: #ffffff;
  width: 91%;
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 10px;
  height: 100px; /*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
  height: calc(
    88px + constant(safe-area-inset-bottom)
  ); /* 直接扩展高度，因为padding-bottom是内边距 */
  height: calc(88px + env(safe-area-inset-bottom)); /* 直接扩展高度 */
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  /* left: 0;
  right: 0;

  height: 65px;
  height: calc(
    58px + constant(safe-area-inset-bottom)
  );
  height: calc(58px + env(safe-area-inset-bottom));
  background: #fff;
  padding: 10px 11px 0 20px;
  box-sizing: border-box;

  text-align: right;
  border-top: 1px solid #e9e9e9; */
}

/* 覆盖van-button的默认样式 */
.van-button {
  height: 35px !important;
  border-radius: 5px;
}

.delete-list {
  display: flex;
  justify-content: flex-end;
  padding-right: 10px;
  margin-top: 8px;
}

.Fa {
  display: flex;
  justify-content: left;
}

.left {
  margin: 10px 0px 10px 15px;
}

.fontstepper {
  margin-left: 15px;
  line-height: 40px;
}

.font {
  margin-left: 15px;
  font-size: 14px;
}

.aa {
  text-align: right;
}

.scrollBar {
  box-sizing: border-box;
  /* height: 550px; */
  /* height: calc(100vh - 266px); */
  /* padding-bottom: 80px; */
  padding-bottom: 130px;
  /* overflow-y: auto; */
}

.scrollBar::-webkit-scrollbar {
  display: none;
}

.close {
  position: "absolute";

  right: 0;
  bottom: 0;
  padding: "5px 16px";
  background: "#fff";
  text-align: right;
  z-index: 1;
}

.client {
  box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 5px 5px;
}

.mysamplebox {
}

/* .Father {
  display: flex;
} */
</style>
<style lang="less" scoped>
// 覆盖vant-filed默认样式
.textarea {
  padding: 0px 16px;

  /deep/ .van-field__label {
    width: 3rem;
  }
}
</style>
